<template>
  <div class="count-box">
    <button @click="sub" class="minus">-</button>
    <input class="inp" type="text" :value="value" @change="handleChange">
    <button @click="add" class="add">+</button>
  </div>
</template>

<script>
export default {
  name: 'CountBox',
  props: {
    value: Number
  },
  methods: {
    add () {
      this.$emit('input', this.value + 1)
    },
    sub () {
      if (this.value <= 1) {
        return
      }
      this.$emit('input', this.value - 1)
    },
    // 输入框的change事件，中间输的过程可以不管你，但是一旦回车或者失焦确认了，我就要拿到你输入框的值
    handleChange (e) {
      console.log(e.target.value)
      const num = +e.target.value // 转数字处理会转成数字或者NaN(如果输入abc这种情况，会变成NaN)
      // 输入了不合法的文本
      if (isNaN(num) || num < 1) {
        e.target.value = this.value
        return
      }
      this.$emit('input', num)
    }
  }
}
</script>

<style lang="less" scoped>
.count-box {
  width: 110px;
  display: flex;

  .add, .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }

  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}
</style>
